import {
  useEffect,
  useState,
  useMemo,
  useCallback,
  forwardRef,
  useImperativeHandle,
  Ref,
  ReactNode,
} from 'react';
import { Input, Select, Table, Tooltip } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { uuid, InbizIcon } from '@inbiz/utils';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import {ControllerInput} from '../ControllerInput'
export type IType = (
  | 'string'
  | 'boolean'
  | 'number'
  | 'object'
  | 'array'
  | 'any'
)[];
export type IValue = {
  id: string;
  name: string;
  value?: string;
  type: IType[number];
  desc?: string;
  root?: boolean; // 判断是否为根节点
  isArrayItem?: boolean; // 判断是不是数组中的项
  children?: IValue;
}[];
export type IInputTable = {
  getValue: () => IValue;
};
function InputTable(
  {
    value,
    typeOption = ['string', 'boolean', 'number', 'object', 'array', 'any'],
    rootOption,
    scroll,
    tooltip = <>
      参数内容:
      <br />
      应用信息（appInfo）、用户信息（userInfo）、页面参数（queryData）、环境变量（cookie）、组件参数（environment）、组件接口请求参数（component）
      <br />
      示例1：@appInfo.xxxx.xxxx.n..
      <br />
      示例2：支持js语法，如{'${data.appInfo.xxx}'}
      ，其中data为所有的参数集合；
      <br />
    </>,
    isController
  }: {
    value?: IValue;
    typeOption?: IType;
    rootOption?: IType;
    scroll?: { y: number };
    tooltip?: ReactNode
    isController?: boolean
  },
  ref: Ref<IInputTable>,
) {
  const [dataSource, $dataSource] = useState<IValue>([]);
  useEffect(() => {
    $dataSource(value || []);
  }, [value]);

  useImperativeHandle(
    ref,
    () => ({
      getValue: () => {
        return dataSource.filter((item) => !!item.name);
      },
    }),
    [dataSource],
  );
  // 添加
  const handleAdd = useCallback((id: string, type: 'next' | 'children') => {
    $dataSource((data) => {
      return updateTreeData(data, id, function (item, index, rows) {
        const addItem = {
          id: uuid(8, 10),
          type: 'string' as IType[number],
          name: '',
          isArrayItem: false,
        };
        if (type === 'next') {
          if (item.isArrayItem) {
            addItem.isArrayItem = true;
            addItem.name = 'Items';
          }
          rows.splice(index + 1, 0, addItem);
        } else {
          if (item.type === 'array') {
            addItem.isArrayItem = true;
            addItem.name = 'Items';
          }
          item.children = [...(item.children || [])];
          item.children.push(addItem);
        }
      });
    });
  }, []);
  // 删除
  const handleDel = useCallback((id: string) => {
    $dataSource((data) => {
      return updateTreeData(data, id, function (item, index, rows) {
        rows.splice(index, 1);
      });
    });
  }, []);
  // 变更数据
  const handleChange = useCallback(
    (id: string, dataIndex: string, value: string) => {
      $dataSource((data) => {
        return updateTreeData(data, id, function (item) {
          item[dataIndex] = value;
          if (dataIndex === 'type') {
            if (value === 'array' || value === 'object') {
              item.children = [];
            } else {
              delete item.children;
            }
          }
        });
      });
    },
    [],
  );
  const columns: ColumnsType<IValue[number]> = useMemo(() => {
    return [
      {
        title: '参数名称',
        dataIndex: 'name',
        key: 'name',
        className: 'nameTd',
        render: (value, recerd) => {
          if (
            (recerd.root &&
              (recerd.type === 'object' || recerd.type === 'array')) ||
            recerd.isArrayItem
          ) {
            return <span className="nametxt">{value}</span>;
          } else {
            return (
              <Input
                defaultValue={value}
                style={{ width: 'auto' }}
                onBlur={(event) =>
                  handleChange(recerd.id, 'name', event.target.value)
                }
              />
            );
          }
        },
      },
      {
        title: (
          <div className="valueTitleBox">
            参数内容
            {
              tooltip && <Tooltip
              color={'#fff'}
              overlayInnerStyle={{ width: 500 }}
              title={
                <div style={{ color: '#000' }}>
                  {tooltip}
                </div>
              }
            >
              <ExclamationCircleOutlined />
            </Tooltip>
            }
          </div>
        ),
        dataIndex: 'value',
        key: 'value',
        render: (value, recerd) => {
          if (recerd.type === 'object' || recerd.type === 'array') {
            return <div className="valueDisabled"></div>;
          } else {
            return (
              isController ? <ControllerInput value={value} onChange={(value) => handleChange(recerd.id, 'value', value)} /> :
              <Input
                defaultValue={value}
                onBlur={(event) =>
                  handleChange(recerd.id, 'value', event.target.value)
                }
              />
            );
          }
        },
      },
      {
        title: '参数类型',
        dataIndex: 'type',
        key: 'type',
        render: (value, recerd) => {
          return (
            <Select
              style={{ width: '100%' }}
              defaultValue={value}
              options={(recerd.root
                ? rootOption || typeOption
                : typeOption
              ).map((item) => ({
                label: item,
                value: item,
              }))}
              onChange={(value) => handleChange(recerd.id, 'type', value)}
            />
          );
        },
      },
      {
        title: '参数说明',
        dataIndex: 'desc',
        key: 'desc',
        render: (value, recerd) => (
          <Input
            defaultValue={value}
            onBlur={(event) =>
              handleChange(recerd.id, 'desc', event.target.value)
            }
          />
        ),
      },
      {
        title: '操作',
        dataIndex: 'option',
        key: 'option',
        render: (_value, recerd) => {
          return (
            <>
              <InbizIcon
                type="icon-node-add"
                style={{ fontSize: 16, cursor: 'pointer' }}
                onClick={() => {
                  handleAdd(
                    recerd.id,
                    recerd.type === 'object' || recerd.type === 'array'
                      ? 'children'
                      : 'next',
                  );
                }}
              />
              {!recerd.root && (
                <InbizIcon
                  type="icon-shanchu-zibiaoge"
                  style={{ marginLeft: 20, fontSize: 16, cursor: 'pointer' }}
                  onClick={() => handleDel(recerd.id)}
                />
              )}
            </>
          );
        },
      },
    ];
  }, [typeOption, rootOption]);
  return (
    <Table
      pagination={false}
      size="small"
      bordered
      columns={columns}
      dataSource={dataSource}
      rowKey="id"
      expandable={{ defaultExpandAllRows: true }}
      scroll={scroll}
    />
  );
}

export default forwardRef(InputTable);

//查找指定节点数据节点
function updateTreeData(
  data: IValue,
  id: string,
  callBack: (row: IValue[number], index: number, data: IValue) => void,
) {
  return updateTreeDataCore(data, id, callBack)[0];
}
function updateTreeDataCore(
  data: IValue,
  id: string,
  callBack: (row: IValue[number], index: number, data: IValue) => void,
) {
  if (Array.isArray(data)) {
    let find = false;
    const newData = [...data];
    const index = newData.findIndex((item) => item.id === id);
    if (index === -1) {
      newData.forEach((item) => {
        if (item.children && !find) {
          const childrenData = updateTreeDataCore(item.children, id, callBack);
          if (childrenData) {
            item.children = childrenData[0];
            find = childrenData[1];
          }
        }
      });
      return [newData, find] as const;
    } else {
      newData[index] = {
        ...newData[index],
      };
      callBack(newData[index], index, newData);
      return [newData, find] as const;
    }
  } else {
    return data;
  }
}


